<script setup lang="ts">
import { ref, nextTick, computed, onUnmounted } from 'vue'
import NvueIcon from '@/pluginPackage/components/nvueIcon/nvue-icon.vue'
import Popup from '@/pluginPackage/liveModule/views/components/chatRoom/components/send/popup.vue'
import { onLoad, onUnload, onHide } from '@dcloudio/uni-app'
import { cartIconName, liveIconName } from '@/pluginPackage/liveModule/views/components/icon-name'
import OngoingGoods from '@/pluginPackage/liveModule/views/components/goods/ongoing-goods.vue'
import MessageMuted from '@/pluginPackage/liveModule/views/components/chatRoom/components/message/message-muted.vue'
import MessageText from '@/pluginPackage/liveModule/views/components/chatRoom/components/message/message-text.vue'
import MessageTip from '@/pluginPackage/liveModule/views/components/chatRoom/components/message/message-tip.vue'
import MessageRemind from '@/pluginPackage/liveModule/views/components/chatRoom/components/message/message-remind.vue'
import FaceEmoji from '@/pluginPackage/liveModule/views/components/chatRoom/components/message/face-emoji.vue'
import { socketTask, MessageType, send } from '../../socket'
import {
  handleTextMessageShowContext,
  handleTipMessageShowContext,
  handleMutedContext,
} from '@/pluginPackage/liveModule/views/components/chatRoom/utils/untis'
import { tim, TIM } from '@/pluginPackage/liveModule/views/components/chatRoom/hooks/index'
import { loginIM } from '@/pluginPackage/liveModule/views/components/chatRoom/index'
import { doDismissGroup } from '@/pluginPackage/liveModule/views/components/chatRoom/apis'

const $props = defineProps({
  disableInput: {
    type: Boolean,
    default: false,
  },
})
let time = null as NodeJS.Timeout | null
const EMOJI_URL =
  ''
const like = ref(false)
const emojiShow = ref(false)
const showSendMessage = ref(false)
const emit = defineEmits(['keyboardheightchange'])
const likeCount = ref(0)
const sendText = ref('发 送')
const inputUpHeight = ref(0)
// px 单位
const inputUpHeightOnce = ref(0)
const inputRef = ref()
// footer 组件高度 rpx
const chat_room_footerHeight = 140
// 弹窗 padding 值 rpx
const popupPadding = 20 * 2
// 弹窗 popup_send_input_Height 值 rpx
const popup_send_input_Height = 80
// 自动回弹
const messageBottom = ref('')
// 消息列表
const messageList = ref<any[]>([])
// 输入框文字
const textM = ref('')
// 禁言定时器
let mutedTimer = null as NodeJS.Timer | null
// 禁言时间
let mutedSecond = 0
let onMessageReceived = function (event: any) {
  messageBottom.value = ''
  event.data.forEach((item: any) => {
    messageList.value = [...messageList.value, { ...item, flow: 'in' }]
  })
  nextTick(() => {
    messageBottom.value = 'message-bottom'
  })
}
tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived)
//
const chat_room_content_computed = computed(() => {
  if (showSendMessage.value) {
    // 弹窗打开时
    const chatMarginButtom = 10
    const height = uni.upx2px(popupPadding) + uni.upx2px(popup_send_input_Height) + chatMarginButtom + inputUpHeightOnce.value + 'px'
    return height
  }
  // 默认 作为 chat_room_content 组件的 margin-buttom
  return chat_room_footerHeight + 'rpx'
})

init()
onUnmounted(() => {
  doDismissGroup({ success: () => {}, error: () => {} })
  time && clearInterval(time)
  socketTask.value && socketTask.value.close()
})

const handleLive = () => {
  like.value = true
  let time = setTimeout(() => {
    likeCount.value++
    like.value = false
    clearTimeout(time)
  }, 300)
}

// socketTask.value
const keyboardheightchange = (e: any) => {
  if (inputUpHeightOnce.value === 0) {
    // 记录软键盘的高度 赋值给 emjeo 组件
    inputUpHeightOnce.value = e.detail.height
  }
  inputUpHeight.value = e.detail.height
  emit('keyboardheightchange', e)
  // 要在表情组件展示后执行
  setTimeout(() => {
    if (e.detail.height === 0 && !emojiShow.value && showSendMessage.value) {
      showSendMessage.value = false
    }
  }, 110)
}
const upper = () => {}
// 处理禁言时间
const handleMutedTime = (second: number) => {
  sendText.value = '禁 言'
  mutedSecond = second
  mutedTimer && clearInterval(mutedTimer)
  mutedTimer = setInterval(() => {
    mutedSecond--
    if (mutedSecond <= 0) {
      mutedTimer && clearInterval(mutedTimer)
      sendText.value = '发 送'
    }
  }, 1000)
}
// 关闭禁言弹框
const handleHideMuted = (id: any) => {
  messageList.value = messageList.value.filter((item) => item.ID !== id)
}
// 处理需要合并的数据
const handleSend = (emo: any) => {
  textM.value += emo.name
}
// 发送表情消息
const sendFaceMessage = async () => {
  if (!textM.value.trim() || sendText.value === '禁 言') return
  messageBottom.value = ''
  const options: any = {
    // @ts-ignore
    // eslint-disable-next-line no-undef
    to: getApp().globalData.groupID,
    conversationType: TIM.TYPES.CONV_GROUP,
    payload: { text: textM.value },
    // @ts-ignore
    // eslint-disable-next-line no-undef
    cloudCustomData: JSON.stringify({ name: getApp().globalData.userInfo.nickname }),
  }
  const message = tim.createTextMessage(options)
  tim
    .sendMessage(message)
    .then(() => {
      messageList.value = [...messageList.value, { ...message, flow: 'out' }]
      nextTick(() => {
        textM.value = ''
        messageBottom.value = 'message-bottom'
      })
    })
    .catch((err: any) => {
      switch (err.code) {
        case 10017:
          uni.showToast({
            icon: 'none',
            title: '禁言中！',
          })
          break
        case 10010:
          uni.showToast({
            icon: 'none',
            title: '主播暂未开启聊天室',
          })
          break
        default:
          uni.showToast({
            icon: 'none',
            title: '发送失败！',
          })
          break
      }
    })
}
const handleEmojiClick = () => {
  if (emojiShow.value) {
    emojiShow.value = false
    // 先关闭表情组件 再弹起键盘
    setTimeout(() => {
      // #ifdef MP-WEIXIN
      // #endif
      // #ifdef APP-PLUS
      inputRef.value.focus()
      // #endif
    }, 500)
  } else {
    uni.hideKeyboard()
    setTimeout(() => {
      emojiShow.value = true
    }, 100)
  }
}
const handleFocus = () => {
  if (emojiShow.value) {
    emojiShow.value = false
  }
}
const handleClickFooterInput = () => {
  if ($props.disableInput) return
  showSendMessage.value = true
  // #ifdef MP-WEIXIN
  // #endif
  // #ifdef APP-PLUS
  inputRef.value.focus()
  // #endif
}
const handleSendMessageClose = () => {
  if (emojiShow.value) {
    emojiShow.value = false
  }
  uni.hideKeyboard()
  // #ifdef MP-WEIXIN
  // #endif
}
function init() {
  loginIM()
  time = setInterval(() => {
    if (socketTask.value && likeCount.value !== 0) {
      const data = {
        type: 'LIKE',
        data: {
          // @ts-ignore
          // eslint-disable-next-line no-undef
          liveId: getApp().globalData.groupID,
          count: likeCount.value,
        },
      } as MessageType
      send(data)
      likeCount.value = 0
    }
  }, 2000)
}
const handleblur = () => {
  // #ifdef MP-WEIXIN
  // #endif
}
</script>

<template>
  <!-- 聊天记录 -->
  <view class="chat_room_content" :style="{ marginBottom: chat_room_content_computed }">
    <scroll-view scroll-y="true" :show-scrollbar="false" class="scroll-Y" :scroll-into-view="messageBottom" @scrolltoupper="upper">
      <view class="chat_room_content_message">
        <template v-for="item in messageList" :key="item.ID">
          <message-muted
            v-if="item.payload?.operationType === 16"
            :text="handleMutedContext(item)"
            :item="item"
            :handle-muted-time="handleMutedTime(item.payload.muteTime)"
            @hide-muted="handleHideMuted"
          />
          <message-remind v-if="!item.isRevoked && item.type === TIM.TYPES.MSG_GRP_SYS_NOTICE" :data="handleTipMessageShowContext(item)" />
          <message-tip v-if="!item.isRevoked && item.type === TIM.TYPES.MSG_GRP_TIP" :data="handleTipMessageShowContext(item)" />
          <message-text
            v-if="item.type === TIM.TYPES.MSG_TEXT"
            :id="item.flow + '-' + item.ID"
            :data="handleTextMessageShowContext(item)"
            :message-data="item"
          />
        </template>
      </view>
      <view id="message-bottom" style="height: 2rpx"></view>
    </scroll-view>
    <!-- 讲解中商品 -->
    <view style="width: 100rpx; height: 1rpx; opacity: 0"></view>
    <!-- <ongoing-goods /> -->
    <!-- 讲解中商品 -->
  </view>
  <!-- 聊天记录 -->
  <!-- 底部输入 点赞 -->
  <view class="chat_room_footer" :style="{ height: chat_room_footerHeight + 'rpx' }">
    <view class="chat_room_footer__left">
      <view class="uni-input" @click="handleClickFooterInput"> <text style="color: #bdb2b2">说点什么吧！</text> </view>
    </view>
    <view class="chat_room_footer__right" :style="{ justifyContent: 'center' }">
      <!-- <view class="chat_room_footer__right__round" @click="popupShow = true">
                        <image
                            class="image_round image_round_left"
                            mode="aspectFit"
                            src=""
                        />
                    </view> -->
      <view class="chat_room_footer__right__round" @tap="handleLive">
        <image
          class="image_round"
          :class="{ image_round_like: like }"
          mode="widthFix"
          src=""
        />
      </view>
    </view>
  </view>
  <!-- 底部输入 点赞 -->
  <!-- 输入框表情弹窗 s -->
  <popup v-model="showSendMessage" border-radius="0" @close="handleSendMessageClose">
    <view class="popup_send">
      <input
        ref="inputRef"
        v-model="textM"
        class="popup_send_input"
        :adjust-position="false"
        placeholder="跟用户说点什么吧！"
        :maxlength="50"
        :placeholder-style="{ color: '#fff' }"
        @keyboardheightchange="keyboardheightchange"
        @focus="handleFocus"
        @blur="handleblur"
      />
      <view class="emoji_css" @click="handleEmojiClick"> <image class="emoji_css" :src="EMOJI_URL"></image> </view>
      <view class="send" :style="{ background: textM && sendText !== '禁 言' ? '#FA3534' : '#FFA1A0' }" @click="sendFaceMessage">
        <text style="color: #fff"> {{ sendText }}</text>
      </view>
    </view>
    <view :style="{ height: inputUpHeightOnce + 'px', width: '100rpx' }"></view>
    <!-- 表情 -->
    <view :style="{ height: (emojiShow ? inputUpHeightOnce : 0) + 'px', position: 'fixed', bottom: 0 }">
      <face-emoji :show="emojiShow" :height="inputUpHeightOnce" @send="handleSend" @handle-send-emoji="sendFaceMessage"></face-emoji>
    </view>
    <!-- 表情 -->
  </popup>
  <!-- 输入框表情弹窗 e -->
  <!-- 商品 弹窗 -->
  <!-- <goods-popup v-model="popupShow">
            <view class="title">
                <text>111</text>
                <nvue-icon font-size="30px" :icon-name="cartIconName" color="red" />
            </view>
        </goods-popup> -->
</template>
<style scoped>
.chat_room_footer {
  position: absolute;
  bottom: 0;
  width: 750rpx;
  height: 140rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
  padding: 0 30rpx;
}
.uni-input {
  color: #fff;
  width: 500rpx;
  height: 80rpx;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 189rpx;
  padding: 0 30rpx;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-direction: row;
}
.chat_room_footer__right {
  flex: 1;
  display: flex;
  justify-content: space-between;
  /* justify-content: center; */
  align-items: center;
  flex-direction: row;
  margin-left: 20rpx;
}
.chat_room_footer__right__round {
  height: 80rpx;
  width: 80rpx;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.image_round {
  height: 60rpx;
  width: 60rpx;
  border-radius: 50%;
  transition: all 0.3s;
  transform: scale(1);
}

.image_round_like {
  transform: scale(0.9);
}
.image_round_left {
  height: 50rpx;
  width: 50rpx;
  border-radius: 0%;
}
.chat_room_content {
  /* max-height: 500rpx; */
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-end;
  padding: 0 30rpx;
  /* overflow: hidden; */
  /* margin-bottom: 140rpx; */
}
.scroll-Y {
  height: 400rpx;
  flex: 1;
}
.send {
  width: 134rpx;
  height: 64rpx;
  background: #fa3534;
  border-radius: 39rpx;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  color: #fff;
}
.popup_send {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.popup_send_input {
  color: #fff;
  width: 450rpx;
  height: 80rpx;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 189rpx;
  padding: 0 30rpx;
}
.chat_room_content_message {
  display: flex;
  flex-direction: column;
}
</style>
<style scoped>
.title {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.emoji_css {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  /* background: #ffa843; */
  position: relative;
}
</style>
